<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\Helper;
use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 动态评论
 */
class MomentComment extends Model
{
    protected $table = 'moment_comment';

    //正常
    const STATUS_OK = 1;
    //删除
    const STATUS_DEL = 0;
    //待审核
    const STATUS_VERIFING = -1;
    //审核不通过
    const STATUS_BAD = -2;

    protected $fillable = [
        "user_id", "moment_id", "content", "commented_id", "parent_comment_id", "commented_user_id", "flag", "top"
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 关联评论
     */
    function commented()
    {
        return $this->belongsTo(MomentComment::class, 'commented_id', 'id');
    }

    /**
     * 通过动态ID获取动态列表
     * @param int $topic_id
     * @return mixed
     */
    static function getList($momentId = 0, $page = 1, $pageNum = 20, $needBuild = false)
    {
        if (!$momentId) return [];
        $where = [
            ['moment_id', $momentId],
            ['flag', self::STATUS_OK],
        ];
        $start = ($page - 1) * $pageNum;
        // $items = self::where($where)->orderBy('id', 'desc')->offset($start)->limit($pageNum)->get()->toArray();
        $items = Db::table('moment_comment')->join('user', function ($join) use ($where) {
            $where[] = ['user.status', User::STATUS_OK];
            $join->on('moment_comment.user_id', '=', 'user.id')->where($where);
        })->orderBy('moment_comment.id', 'desc')->select(['moment_comment.*'])->offset($start)->limit($pageNum)->get()->toArray();
        if ($needBuild) {
            $data = [];
            array_walk($items, function ($item) use (&$data) {
                $comment = self::buildItem($item);
                $comment && array_push($data, $comment);
            });
            return $data;
        }
        return $items;
    }

    /**
     * 封装动态评论数据
     * @param $item
     * @return array
     */
    static function buildItem($comment = null, $userId = 0)
    {
        if (!$comment) return null;
        if (!is_array($comment)) $comment = (array)$comment;
        $user = UserProfile::getProfile($comment['user_id']);
        if (!$user) {
            log_info(__CLASS__ . "==buildItem==noUser==" . $comment['id']);
            return null;
        }
        $ret = [
            'comment_id' => $comment['id'],
            'content' => $comment['content'],
            'user_id' => $comment['user_id'],
            'nickname' => $user->nick_name,
            'gender' => $user->gender,
            'avatar' => $user->avatar,
            'like_num' => $comment['like_num'] ?? 0,
            'is_liked' => CommentLike::checkLike($userId, $comment['id']), //是否点赞评论
            'comment_time' => Helper::showOnlineTime((string) $comment['created_at']),
            'commented_user' => null,
        ];
        //被回复的用户信息
        if ($comment['commented_id']) {
            $atComment = MomentComment::find($comment['commented_id']);
            $atUser = UserProfile::getProfile($atComment->user_id);
            $ret['commented_user'] = [
                'gender' => $atUser->gender,
                'nickname' => $atUser->nick_name,
                'user_id' => $atUser->id,
                'avatar' => $atUser->avatar,
            ];
        }
        return $ret;
    }

    /**
     * 更新喜欢数
     */
    static function updateLikeNum($comentId = 0, $likeNum = 1)
    {
        return $likeNum > 0 ?
            self::where('id', $comentId)->limit(1)->increment('like_num', abs($likeNum)) :
            self::where('id', $comentId)->limit(1)->decrement('like_num', abs($likeNum));
    }
}
